import Taro from '@tarojs/taro';

import { Command } from '../constant';
import { Dispatch } from 'typings';
import { IAllReducerProps } from '../types';
import { getReducerData } from '@/redux/store';
import { extraPathsValue } from '@/redux/util';

import api from 'api';
const regexTel = /^134[0-8]\d{7}$|^13[^4]\d{8}$|^14[5-9]\d{8}$|^15[^4]\d{8}$|^16[6]\d{8}$|^17[0-8]\d{8}$|^18[\d]{9}$|^19[1,5,8,9]\d{8}$/;

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },

    /**
     * 提交
     */
    async submit() {
      let {
        consigneeName,
        consigneeNumber,
        areaIds,
        deliveryAddress,
        isDefaltAddress,
        deliveryAddressId,
      } = getData().main;

      if (consigneeName == '') {
        Taro.showToast({
          title: '请填写收货人',
          icon: 'none',
          duration: 2000,
        });
        return false;
      } else if (consigneeNumber == '') {
        Taro.showToast({
          title: '请填写手机号码',
          icon: 'none',
          duration: 2000,
        });
        return false;
      } else if (!regexTel.test(consigneeNumber)) {
        Taro.showToast({
          title: '手机号格式有误',
          icon: 'none',
          duration: 2000,
        });
        return false;
        //还存在一种情况为[null,null,null,-1]
      } else if (areaIds.length == 0) {
        Taro.showToast({
          title: '请选择所在地区',
          icon: 'none',
          duration: 2000,
        });
        return false;
      } else if (deliveryAddress == '') {
        Taro.showToast({
          title: '请填写详细地址',
          icon: 'none',
          duration: 2000,
        });
        return false;
      }
      let areaIdsMap = {
        provinceId: areaIds[0],
        cityId: areaIds[1],
        areaId: areaIds[2],
      } as any;
      areaIdsMap.streetId = areaIds[3] ? areaIds[3] : 0;
      let address;
      try {
        await api.customerDeliveryAddressController.updateAddress({
          consigneeName,
          consigneeNumber,
          ...areaIdsMap,
          deliveryAddress,
          isDefaltAddress,
          deliveryAddressId,
        });
      } catch (e) {
        Taro.showToast({
          title: e.message,
          icon: 'none',
          duration: 2000,
        });
        return;
      }
      Taro.showToast({
        title: '保存成功！',
        icon: 'none',
        duration: 2000,
      });
      Taro.navigateBack();
    },

  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageAddressEditDMain'),
  };
}
